/*
 * Copyright 2018-2019 KunMinX
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wanchuang.hepos.ui.page.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.architecture.utils.Utils;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.data.repository.Apis;
import com.wanchuang.hepos.bridge.request.LoginRequestViewModel;
import com.wanchuang.hepos.bridge.state.login.ForgetPasswordViewModel;
import com.wanchuang.hepos.databinding.FragmentForgetPasswordBinding;
import com.wanchuang.hepos.net.NetworkManager;
import com.wanchuang.hepos.net.interfaces.OnRequestCallBack;
import com.wanchuang.hepos.proto.PBPublicOuterClass;
import com.wanchuang.hepos.ui.base.BaseFragment;


/**
 * Create by KunMinX at 19/10/29
 */
public class ForgetPasswordFragment extends BaseFragment {

    private FragmentForgetPasswordBinding mBinding;
    private ForgetPasswordViewModel mForgetPasswordModel;
    private LoginRequestViewModel mLoginRequestViewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mForgetPasswordModel = ViewModelProviders.of(this).get(ForgetPasswordViewModel.class);
        mLoginRequestViewModel = ViewModelProviders.of(this).get(LoginRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_forget_password, container, false);
        mBinding = FragmentForgetPasswordBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mForgetPasswordModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mLoginRequestViewModel.getErrorString().observe(this, this::showShortToast); // 错误返回
        mLoginRequestViewModel.getResultString().observe(this, s -> {  // 成功返回
            showShortToast(s);
            nav().navigateUp();
        });
        mLoginRequestViewModel.getCodeString().observe(this, s -> {  // 获取验证码
            showShortToast(s);
            mForgetPasswordModel.startCode.set(true);

        });
    }

    @Override
    public void onStop() {
        if (Utils.isAppForeground()||!mSharedViewModel.isLoading.getValue()) {
            mForgetPasswordModel.startCode.set(false);
        }
        super.onStop();
    }


    public class ClickProxy {
        public void submit() {
           String mPhone = mForgetPasswordModel.phone.get();
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }

            if (mPhone.length() != 11) {
                showShortToast("请输入11位手机号码");
                return;
            }
            String code =mForgetPasswordModel.code.get();
            if (TextUtils.isEmpty(code)) {
                showShortToast("请输入验证码");
                return;
            }
            String pwd = mForgetPasswordModel.password.get();
            if (TextUtils.isEmpty(pwd)) {
                showShortToast("请输入密码");
                return;
            }
            if (pwd.length() < 6 || pwd.length() > 16) {
                showShortToast("请输入6-16位长度的密码");
                return;
            }
            String confirmPwd =  mForgetPasswordModel.checkPassword.get();
            if (!pwd.equals(confirmPwd)) {
                showShortToast("两次输入密码不一致，请重新输入");
                return;
            }


            PBPublicOuterClass.get_form_token.Builder builder = PBPublicOuterClass.get_form_token.newBuilder();
            builder.setAction("find_password");
            PBPublicOuterClass.get_form_token data = builder.build();
            NetworkManager.INSTANCE.post(Apis.get_form_token, data.toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    PBPublicOuterClass.get_form_token resp = PBPublicOuterClass.get_form_token.parseFrom(bytes);
                    mLoginRequestViewModel.forgetPassword(mPhone,code,pwd,resp.getFormToken());
                }

                @Override
                public void onError(int code, String errorMessage) {
                    showShortToast(errorMessage);
                }
            });



        }

        public void back() {
            nav().navigateUp();
        }

        public void getCode() {
            String mPhone =  mForgetPasswordModel.phone.get();
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            if (mPhone.length() != 11) {
                showShortToast("请输入11位手机号码");
                return;
            }
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            mLoginRequestViewModel.getCode(mPhone,"3");
        }

        /**
         * 设置密码是否为明文显示
         */
        public void checkBoxOne(boolean isChecked) {
            TransformationMethod method;
            if (isChecked) {
                method = PasswordTransformationMethod.getInstance();
            } else {
                method = HideReturnsTransformationMethod.getInstance();
            }
            mForgetPasswordModel.formatOne.set(method);
        }

        public void checkBoxTow(boolean isChecked) {
            TransformationMethod method;
            if (isChecked) {
                method = PasswordTransformationMethod.getInstance();
            } else {
                method = HideReturnsTransformationMethod.getInstance();
            }
            mForgetPasswordModel.formatTwo.set(method);
        }
    }
}
